package testLibrerie;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;

import componenti.statistica.Esponenziale;
import componenti.statistica.GeneratoreCasuale;

public class Charts {
	public static void main(String[] args) {
		// creo il vettore di numeri casuali
		double[] casual = new double[50];
		double[] real;
		for (int i = 0; i < casual.length; i++) {
			casual[i] = new Random().nextDouble();
		}
		real = GeneratoreCasuale.getSimulation(new Esponenziale(2), casual);
		final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
		for (int i = 0; i < casual.length; i++) {
			dataset.addValue(real[i],
					"" + new DecimalFormat("#.##").format(1 - casual[i]),
					"Numero Casuale");
		}
		JFreeChart chart = ChartFactory.createBarChart("Bar Chart Demo", // chart
																			// title
				"Category", // domain axis label
				"Value", // range axis label
				dataset, // data
				PlotOrientation.VERTICAL, // orientation
				true, // include legend
				true, // tooltips?
				false // URLs?
				);

		ChartPanel chartPanel = new ChartPanel(chart, false);
		chartPanel.setPreferredSize(new Dimension(500, 270));
		ChartFrame cf = new ChartFrame("Prova", chart);
		cf.setLayout(new BorderLayout());
		final JButton b = new JButton("Ricalcola");
		cf.add(b,BorderLayout.SOUTH);
		b.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				double[] casual = new double[50];
				double[] real;
				for (int i = 0; i < casual.length; i++) {
					casual[i] = new Random().nextDouble();
				}
				real = GeneratoreCasuale.getSimulation(new Esponenziale(2),
						casual);
				dataset.clear();
				for (int i = 0; i < casual.length; i++) {
					dataset.addValue(
							real[i],
							""
									+ new DecimalFormat("#.##")
											.format(1 - casual[i]),
							"Numero Casuale");
				}
				((ChartFrame) b.getParent().getParent().getParent().getParent())
						.pack();}
		});
		
		cf.setLocationByPlatform(true);
		cf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		cf.pack();
		cf.setVisible(true);
	}
}
